<?php

namespace WSRoute;

use FastRoute\Dispatcher;
use Response\JsonResponse;

class Provider
{
    /**
     *
     * @var FastRoute\simpleDispatcher a$dispathcer 路由分发器
     */
    protected $dispatcher;
    /**
     * 注册路由
     * @return void
     */
    public function boot()
    {
        $this->dispatcher = \FastRoute\simpleDispatcher(function(\FastRoute\RouteCollector $route) {
            $route->addGroup('/client', function (\FastRoute\RouteCollector $r) {
                $r->addRoute('get', '/index', [\Controller\Client\IndexController::Class, 'index']);
                $r->addRoute('get', '/login', [\Controller\Client\IndexController::Class, 'login']);
                $r->addRoute('get', '/heartBeat', [\Controller\Client\HeartBeatController::Class, 'index']);
            });

            $route->addGroup('/server', function (\FastRoute\RouteCollector $r) {
                $r->addRoute('post', '/notification/orderCreated/{id}', [\Controller\Server\NotificationController::Class, 'orderCreated']);
            });
        });
    }

    /**
     * 分发路由并返回处理结果
     *
     * @param $method string 路由方法
     * @param $uri string 地址
     */
    public function parse($method, $uri, $request, $meta = null)
    {
        $routeResult = $this->dispatcher->dispatch($method, $uri);
        switch ($routeResult[0]) {
            case Dispatcher::FOUND:
                return $this->handler($routeResult[1], $routeResult[2], $request, $meta);
                break;
            default:
                return $this->withError($routeResult);
                break;
        }
    }

    public function handler($handler, $vars, $request, $meta)
    {
        $controller = new $handler[0]($request, $meta);
        return call_user_func_array([$controller, $handler[1]], $vars);
    }

    public function withError($info)
    {
        switch ($info[0]) {
            case Dispatcher::NOT_FOUND:
                return new JsonResponse(404, 0, 'Not Found');
            case Dispatcher::METHOD_NOT_ALLOWED:
                return new JsonResponse(405, 0, 'Method Not Allowed');
        }
    }
}
